package com.fasc.open.api.client;

import com.fasc.open.api.bean.base.BaseRes;
import com.fasc.open.api.bean.req.corpmanage.OpenCorpAuthUrlReq;
import com.fasc.open.api.constants.EUIConstants;
import com.fasc.open.api.constants.RequestConstants;
import com.fasc.open.api.enums.common.EuiEnvironmentEnum;
import com.fasc.open.api.utils.crypt.FddCryptUtil;
import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

public class EUIClient {
    private OpenApiClient openApiClient;

    public EUIClient(OpenApiClient openApiClient) {
        this.openApiClient = openApiClient;
    }

    public BaseRes<String> getOpenCorpAuthorizeUrl(OpenCorpAuthUrlReq req, EuiEnvironmentEnum environmentEnum) throws Exception {
        //H5会自动适配
        String url = EUIConstants.SERVICE_AUTHORIZE;
        Map<String, String> params = new HashMap<>();
        params.put("appId", openApiClient.getAppId().toUpperCase());
        params.put("openCorpId", req.getOpenCorpId());
        params.put("corpName", req.getCorpName());
        params.put("redirectUrl", req.getRedirectUrl());
        params.put("authScopes", req.getAuthScopes());
        String timestamp = String.valueOf(System.currentTimeMillis());
        String sortParam = FddCryptUtil.sortParameters(params);
        String signature = FddCryptUtil.sign(sortParam, timestamp, openApiClient.getAppSecret());
        params.put(RequestConstants.EUI_TIMESTAMP, timestamp);
        params.put(RequestConstants.EUI_SIGNATURE, signature);
        sortParam = FddCryptUtil.sortParameters(params);
        String resultUrl = String.format(environmentEnum.getValueInFact(), openApiClient.getAppId()).concat(url)
                .concat(sortParam);
        BaseRes<String> baseRes = new BaseRes<>();
        baseRes.setData(resultUrl);
        baseRes.setCode(RequestConstants.SUCCESS_CODE);
        baseRes.setHttpStatusCode(HttpStatus.SC_OK);
        return baseRes;
    }
}
